package com.jy.adscm.security.browser.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jy.adscm.annotation.AdscmLogger;
import com.jy.adscm.bean.system.JyUser;
import com.jy.adscm.core.dao.mysql.AdscmLogMapper;
import com.jy.adscm.security.support.SimpleResponse;
import com.jy.adscm.security.utils.AdscmSecurityUtils;
import com.jy.adscm.security.utils.Token;
import com.jy.adscm.utils.AdscmBaseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yyy
 * @ClassName AdscmFormAuthenticationFailureHandler
 * @Description 登录失败处理逻辑
 * @date 2018/7/26 15:55
 */
@Component
public class AdscmFormAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    AdscmLogMapper adscmLogMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        logger.info("登录失败 ...");

        try {
            logger.info("写登录日志...");
            JyUser user = new JyUser();
            user.setUsername(httpServletRequest.getParameter("username"));
            AdscmSecurityUtils.getInstance().writeLoginLog(user,AdscmBaseUtils.getInstance().getIPAddress(httpServletRequest),"系统登录",user.getUsername()+" ; "+httpServletRequest.getParameter("password"),this.getClass().getName()+".onAuthenticationFailure","失败",e.getMessage(),adscmLogMapper);
        }catch (Exception e1){
            logger.error("写登录日志异常...",e1);
        }

        AdscmSecurityUtils.getInstance().printMsgByResponse("401",e.getMessage(),httpServletResponse,objectMapper);
    }
}
